//
//  LGConsultRecordAddController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/10/18.
//

#import "LGConsultRecordAddController.h"
//病情概览
#import "LGDiseaseOverviewController.h"
//添加、编辑手上史
#import "LGFollowOperationController.h"
//检验检查 - 上传报告
#import "LGUploadReportPhotoController.h"
#import "LGReportingCenterController.h"//报告中心
//添加核心指标
#import "LGMainInspectAddController.h"

//添加、编辑药物
#import "LGFollowAddMedicineController.h"
#import "LGFollowStopMedicineController.h"

//要返回的Controller
#import "LGHomeViewController.h"//首页
#import "LGFullScheduleController.h"//全部日程


#import "LGDiseaseOverviewHeaderView.h"
//Cell
//基本信息
#import "LGConsultRecordBasicCell.h"
//按钮选择
#import "LGConsultRecordItemCell.h"
//共病
#import "LGConsultRecordDiseaseCell.h"
//吸烟、饮酒史
#import "LGConsultRecordHistoryCell.h"
//手术信息
#import "LGConsultRecordSurgeryCell.h"
//病情描述
#import "LGConsultRecordDescCell.h"
//体征监测
#import "LGConsultRecordMonitorCell.h"
//检验检查
#import "LGConsultRecordInpectCell.h"
//用药记录
#import "LGConsultRecordMedicineCell.h"
//用药记录-日期
#import "LGConsultRecordDateCell.h"
//选择心功能等级
#import "LGConsultRecordCardiacView.h"
//
#import "LGMedicineStatisticAlertView.h"
#import "LGPickerViewMax.h"
@interface LGConsultRecordAddController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,LGConsultRecordItemDelegate,LGConsultRecordDiseaseDelegate,LGConsultRecordHistoryDelegate,LGConsultRecordDescDelegate>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIView *bottomeView;
/**   */
@property (nonatomic , strong)NSArray *sectionArray;
/**  接诊医生 */
@property (nonatomic , strong)NSArray *doctorArray;
/**  类型 */
@property (nonatomic , strong)NSArray *typeArray;
/**  问诊需求 */
@property (nonatomic , strong)NSArray *needArray;
/**  共病 */
@property (nonatomic , strong)NSArray *diseaseArray;
/**  吸烟史 */
@property (nonatomic , strong)NSDictionary *smokeDic;
/**  饮酒史 */
@property (nonatomic , strong)NSDictionary *drinkDic;
/**  手术列表 */
@property (nonatomic , strong)NSArray *surgeryArray;
/**  检查图片 */
@property (nonatomic , strong)NSArray *inspectArray;
/**  用药记录 */
@property (nonatomic , strong)NSMutableArray *medicineArray;
@property (nonatomic , strong)NSArray *doseArray;
@property (nonatomic , strong)NSArray *rateArray;
/**  病情描述 */
@property (nonatomic , copy)NSString *descContent;
/**  心功能等级 */
@property (nonatomic , strong)NSArray *heartArray;
/**   */
@property (nonatomic , strong)NSMutableDictionary *resultDic;
/**  是否可以编辑接诊医生和序号 */
@property (nonatomic , assign)BOOL canEditBasic;

@end

@implementation LGConsultRecordAddController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.inspectArray = @[];
    self.diseaseArray = @[];
    self.smokeDic = @{};
    self.drinkDic = @{};
    self.canEditBasic = self.isAdd;
    self.navigationView.title = (self.isAdd == YES)?@"添加咨询记录":@"完善咨询记录";
    self.navigationView.rightBtn.titleLabel.font = LGFontWeight(14, UIFontWeightMedium);
    [self.navigationView.rightBtn setTitle:@"病情概览" forState:UIControlStateNormal];
    [self.navigationView.rightBtn setTitleColor:[UIColor colorWithString:@"#4C87FD"] forState:UIControlStateNormal];
    [self.navigationView.rightBtn addTarget:self action:@selector(checkDiseaseOverviewAction) forControlEvents:UIControlEventTouchUpInside];
    self.followDate = (_followDate && _followDate.length>0)?_followDate:@"";
    self.sectionArray = @[@"基本信息",@"手术信息",@"病情描述",@"体征监测",@"检验检查",@"用药记录"];
    [self.view addSubview:self.tableView];
    [self createBottomView];
    [self requestData];
    [self requestSurgeryData];
    [self requestDoseData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestSurgeryData) name:@"RefreshSurgeryData" object:nil];
}

-(void)backButtonAction{
    NSArray *tempArray = self.navigationController.viewControllers;
    for (NSInteger i= tempArray.count-1; i>=0; i--) {
        UIViewController *controller = tempArray[i];
        if([controller isKindOfClass:[LGFullScheduleController class]]){
            //返回全部日程
            [self.navigationController popToViewController:controller animated:YES];
            return;
        }
        if([controller isKindOfClass:[LGHomeViewController class]]){
            //返回首页
            [self.navigationController popToViewController:controller animated:YES];
            return;
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)setFollowDate:(NSString *)followDate{
    _followDate = followDate;
    if(followDate.length>0){
        //过去日期不能保存
        NSDateFormatter *format = [[NSDateFormatter alloc]init];
        [format setDateFormat:@"yyyy-MM-dd"];
        NSDate *followdate = [format dateFromString:followDate];
        NSComparisonResult result = [[NSCalendar currentCalendar] compareDate:followdate toDate:[NSDate date] toUnitGranularity:NSCalendarUnitDay];
        if(result == NSOrderedAscending){
            //过去
            self.bottomeView.hidden = YES;
            self.tableView.frame = CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight);
        }else{
            //现在或未来
            self.bottomeView.hidden = NO;
            self.tableView.frame = CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight-viewPix(72)-bottomSafeBarHeight/3.0);
        }
    }
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.Followup/followupEditInit" parameters:@{@"patient_id":self.patientid,@"followup_date":self.followDate} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.canEditBasic = [returnData[@"appintment_ID"] integerValue]>0?NO:YES;
            self.followDate = LGNSString(returnData[@"followup_date"]);
            self.doctorArray = returnData[@"doctors_selects"];
            self.typeArray = returnData[@"followup_type_selects"];
            self.needArray = returnData[@"follow_needs_selects"];
            self.diseaseArray = returnData[@"diseasesAry"];
            self.smokeDic = returnData[@"xiysobject"];
            self.drinkDic = returnData[@"yinjsobject"];
            self.inspectArray = returnData[@"recordImages"];
            self.medicineArray = [NSMutableArray arrayWithArray:returnData[@"mdicial_advice"]];
            self.descContent = LGNSString(returnData[@"followup_content"]);
            self.heartArray = returnData[@"nyha_selects"];
            NSDictionary *tempDic = @{@"patient_id":self.patientid,
                                      @"followup_date":LGNSString(returnData[@"followup_date"]),
                                      @"realname":LGNSString(returnData[@"realname"]),
                                      @"gender":LGNSString(returnData[@"gender"]),
                                      @"hospital_bano":LGNSString(returnData[@"hospital_bano"]),
                                      @"system_user_id":LGNSString(returnData[@"system_user_id"]),
                                      @"followup_type":LGNSString(returnData[@"followup_type"]),
                                      @"followup_no":LGNSString(returnData[@"followup_no"]),
                                      @"follow_needs":LGNSString(returnData[@"follow_needs"]),
                                      @"followup_content":LGNSString(returnData[@"followup_content"]),
                                      @"sbp":LGNSString(returnData[@"sbp"]),
                                      @"dbp":LGNSString(returnData[@"dbp"]),
                                      @"pulse":LGNSString(returnData[@"pulse"]),
                                      @"height":LGNSString(returnData[@"height"]),
                                      @"weight":LGNSString(returnData[@"weight"]),
                                      @"acvalue":LGNSString(returnData[@"acvalue"]),
                                      @"nyha":LGNSString(returnData[@"nyha"]),@"doctor_name":@""};
            self.resultDic = [NSMutableDictionary dictionaryWithDictionary:tempDic];
            for (NSDictionary *tempDic in self.doctorArray) {
                if([LGNSString(tempDic[@"system_user_id"]) isEqualToString:LGNSString(self.resultDic[@"system_user_id"])]){
                    [self.resultDic setValue:LGNSString(tempDic[@"doctor_name"]) forKey:@"doctor_name"];
                    break;
                }
            }
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)requestSurgeryData{
    [RequestUtil withPOST:@"/doctor/patient.Followup/followupSurgery" parameters:@{@"patient_id":self.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.surgeryArray = returnData;
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)requestDoseData{
    [RequestUtil withPOST:@"/doctor/patient.Followup/takeFrequency" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.doseArray = returnData[@"take_dose"];
            self.rateArray = returnData[@"take_frequency"];
        }
    } error:^(NSError *error) {
        
    }];
}

//保存数据
-(void)saveDataAction{
    NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithDictionary:self.resultDic];
    [resultDic removeObjectForKey:@"realname"];
    [resultDic removeObjectForKey:@"hospital_bano"];
    [resultDic removeObjectForKey:@"doctor_name"];
    [resultDic setValue:[ObjectTool objectToJson:self.smokeDic] forKey:@"xiysobject"];
    [resultDic setValue:[ObjectTool objectToJson:self.drinkDic] forKey:@"yinjsobject"];
    [resultDic setValue:[ObjectTool objectToJson:self.diseaseArray] forKey:@"diseasesAry"];
    [resultDic setValue:[ObjectTool objectToJson:self.inspectArray] forKey:@"recordImages"];
    [resultDic setValue:[ObjectTool objectToJson:self.medicineArray] forKey:@"mdicial_advice"];
    
    if(LGNSString(resultDic[@"system_user_id"]).length == 0){
        [TooltipView showMessage:@"请选择咨询医生" offset:0];
        return;
    }
    
    if(LGNSString(resultDic[@"followup_no"]).length == 0){
        [TooltipView showMessage:@"请输入咨询序号" offset:0];
        return;
    }
    
    if(LGNSString(resultDic[@"followup_type"]).length == 0){
        [TooltipView showMessage:@"请选择类型" offset:0];
        return;
    }
    
    NSString *followNeeds = LGNSString(resultDic[@"follow_needs"]);
    if(followNeeds.length == 0 || [followNeeds isEqualToString:@"<null>"]){
        [TooltipView showMessage:@"请选择咨询需求" offset:0];
        return;
    }
    
    NSString *sbp = LGNSString(resultDic[@"sbp"]);
    NSString *dbp = LGNSString(resultDic[@"dbp"]);
    NSString *pulse = LGNSString(resultDic[@"pulse"]);
    if(!(sbp.length == 0 && dbp.length == 0 && pulse.length == 0) && !(sbp.length > 0 && dbp.length > 0 && pulse.length > 0)){
        [TooltipView showMessage:@"高压、低压、心率 3项要同时填写" offset:0];
        return;
    }
    [RequestUtil withPOST:@"/doctor/patient.Followup/saveFollowupNew" parameters:resultDic withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [TooltipView showMessage:@"保存成功" offset:0];
            [self backButtonAction];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}

//病情概览
-(void)checkDiseaseOverviewAction{
    LGDiseaseOverviewController *controller = [[LGDiseaseOverviewController alloc]init];
    controller.patientid = self.patientid;
    controller.diseaseCode = self.diseaseCode;
    controller.levelid = self.levelid;
    [self.navigationController pushViewController:controller animated:YES];
}

//就诊序号
-(void)indexNumberEditingChanged:(UITextField *)textField{
    [self.resultDic setValue:textField.text forKey:@"followup_no"];
}

//选择就诊医生
-(void)selectDoctorAction{
    if(self.doctorArray.count>0){
        NSMutableArray *tempArray = [NSMutableArray array];
        NSString *doctorName = @"";
        for (NSDictionary *tempDic in self.doctorArray) {
            [tempArray addObject:LGNSString(tempDic[@"doctor_name"])];
            if([LGNSString(tempDic[@"system_user_id"]) isEqualToString:LGNSString(self.resultDic[@"system_user_id"])]){
                doctorName = LGNSString(tempDic[@"doctor_name"]);
            }
        }
        LGPickerViewMax *pickerView = [[LGPickerViewMax alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        pickerView.titleLabel.text = @"选择接诊医生";
        pickerView.pickArry = @[tempArray];
        pickerView.selectStr = doctorName;
        [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
        __weak typeof(self) weakSelf = self;
        pickerView.selectPickViewIndex = ^(NSArray *indexArray) {
            NSInteger index = [indexArray[0] integerValue];
            NSDictionary *tempDic = weakSelf.doctorArray[index];
            [weakSelf.resultDic setValue:LGNSString(tempDic[@"system_user_id"]) forKey:@"system_user_id"];
            [weakSelf.resultDic setValue:LGNSString(tempDic[@"doctor_name"]) forKey:@"doctor_name"];
            [weakSelf.tableView reloadData];
        };
    }else{
        [self requestData];
    }
}

//类型 、 问诊需求
-(void)itemSelectResult:(NSString *)result type:(NSString *)type{
    if ([type isEqualToString:@"radio"]) {
        //类型
        [self.resultDic setValue:result forKey:@"followup_type"];
    }else{
        //问诊需求
        [self.resultDic setValue:result forKey:@"follow_needs"];
    }
    [self.tableView reloadData];
}

//共病
-(void)diseaseItemSelect:(NSArray *)resultArray{
    self.diseaseArray = resultArray;
}

//是否有吸烟、饮酒史
-(void)haveSmokeOrDrinkHistory:(NSString *)type have:(NSString *)have{
    if([type isEqualToString:@"smoke"]){
        NSMutableDictionary *smokeDic = [NSMutableDictionary dictionaryWithDictionary:self.smokeDic];
        [smokeDic setValue:have forKey:@"sfxy"];
        self.smokeDic = smokeDic;
    }else{
        NSMutableDictionary *drinkDic = [NSMutableDictionary dictionaryWithDictionary:self.drinkDic];
        [drinkDic setValue:have forKey:@"sfyj"];
        self.drinkDic = drinkDic;
    }
    [self.tableView reloadData];
}

//是否戒烟、戒酒
-(void)haveStopedSmokeOrDrink:(NSString *)type stoped:(NSString *)stoped{
    if([type isEqualToString:@"smoke"]){
        NSMutableDictionary *smokeDic = [NSMutableDictionary dictionaryWithDictionary:self.smokeDic];
        [smokeDic setValue:stoped forKey:@"sfjy"];
        self.smokeDic = smokeDic;
    }else{
        NSMutableDictionary *drinkDic = [NSMutableDictionary dictionaryWithDictionary:self.drinkDic];
        [drinkDic setValue:stoped forKey:@"sfjj"];
        self.drinkDic = drinkDic;
    }
    [self.tableView reloadData];
}

//吸烟、饮酒年限
-(void)smokeOrDrinkYearChanged:(NSString *)type year:(NSString *)year{
    if([type isEqualToString:@"smoke"]){
        NSMutableDictionary *smokeDic = [NSMutableDictionary dictionaryWithDictionary:self.smokeDic];
        [smokeDic setValue:year forKey:@"year"];
        self.smokeDic = smokeDic;
    }else{
        NSMutableDictionary *drinkDic = [NSMutableDictionary dictionaryWithDictionary:self.drinkDic];
        [drinkDic setValue:year forKey:@"year"];
        self.drinkDic = drinkDic;
    }
}

//病情描述-文字输入
-(void)diseaseDescriptionChanged:(NSString *)content{
    [self.resultDic setValue:content forKey:@"followup_content"];
}


//体征监测 -- 输入
-(void)monitorTextFiledEditingChanged:(UITextField *)textField{
    NSString *content = textField.text;
    if (textField.tag == 2000) {
        //高压
        content = (content.length>3)?[content substringToIndex:3]:content;
        [self.resultDic setValue:content forKey:@"sbp"];
        
    }else if (textField.tag == 2001){
        //低压
        content = (content.length>3)?[content substringToIndex:3]:content;
        [self.resultDic setValue:content forKey:@"dbp"];
        
    }else if (textField.tag == 2002){
        //心率
        content = (content.length>3)?[content substringToIndex:3]:content;
        [self.resultDic setValue:content forKey:@"pulse"];
        
    }else if (textField.tag == 2003){
        //身高
        content = (content.length>5)?[content substringToIndex:5]:content;
        [self.resultDic setValue:content forKey:@"height"];
        
    }else if (textField.tag == 2004){
        //体重
        content = (content.length>5)?[content substringToIndex:5]:content;
        [self.resultDic setValue:content forKey:@"weight"];
        
    }else if (textField.tag == 2005){
        //腹围
        content = (content.length>5)?[content substringToIndex:5]:content;
        [self.resultDic setValue:content forKey:@"acvalue"];
    }
}

//选择心功能等级
-(void)selectHeartGradeAction{
    [self.view endEditing:YES];
    LGConsultRecordCardiacView *cardiacView = [[LGConsultRecordCardiacView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    cardiacView.dataArray = self.heartArray;
    cardiacView.content = LGNSString(self.resultDic[@"nyha"]);
    [[UIApplication sharedApplication].keyWindow addSubview:cardiacView];
    __weak typeof(self) weakSelf = self;
    cardiacView.cardiacSelectResult = ^(NSString * _Nonnull content) {
        [weakSelf.resultDic setValue:content forKey:@"nyha"];
        [weakSelf.tableView reloadData];
    };
}

//查看全部 - 检验检查
-(void)checkMoreInspectAction{
    [self.view endEditing:YES];
    LGReportingCenterController *controller = [[LGReportingCenterController alloc]init];
    controller.patientid = self.patientid;
    controller.diseaseCode = self.diseaseCode;
    controller.currentIndex = 0;
    [self.navigationController pushViewController:controller animated:YES];
}

//上传报告
-(void)uploadInspectReport{
    [self.view endEditing:YES];
    LGUploadReportPhotoController *controller = [[LGUploadReportPhotoController alloc]init];
    controller.photoArray = self.inspectArray;
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.uploadPhotoReportSuccess = ^(NSArray * _Nonnull photoArray) {
        weakSelf.inspectArray = photoArray;
        [weakSelf.tableView reloadData];
    };
}
//添加核心指标
-(void)addCoreIndicators{
    [self.view endEditing:YES];
    LGMainInspectAddController *controller = [[LGMainInspectAddController alloc]init];
    controller.patientid = self.patientid;
    controller.fullowDate = self.followDate;
    [self.navigationController pushViewController:controller animated:YES];
}

//添加手术史、药物
-(void)addButtonTouched:(UIButton *)sender{
    [self.view endEditing:YES];
    if(sender.tag == 1001){
        //添加手术史
        LGFollowOperationController *controller = [[LGFollowOperationController alloc]init];
        controller.patientid = self.patientid;
        [self.navigationController pushViewController:controller animated:YES];
    }else{
        //添加药物
        LGFollowAddMedicineController *controller = [[LGFollowAddMedicineController alloc]init];
        [self.navigationController pushViewController:controller animated:YES];
        __weak typeof(self) weakSelf = self;
        controller.addMedicineRecord = ^(NSDictionary * _Nonnull tempDic) {
            [weakSelf.medicineArray addObject:tempDic];
            [weakSelf.tableView reloadData];
        };
    }
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sectionArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        //基本信息 --  饮酒史
        return 6;
    }else if (section == 1){
        //手术信息
        return self.surgeryArray.count;
    }else if (section == 2){
        //病情描述
        return 1;
    }else if (section == 3){
        //体征监测
        return 1;
    }else if (section == 4){
        //检验检查
        return 1;
    }else if (section == 5){
        //用药记录
        return self.medicineArray.count>0?self.medicineArray.count+1:0;
    }else{
        return 0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        if(indexPath.row == 0){
            //基本信息
            LGConsultRecordBasicCell *basicCell = [tableView dequeueReusableCellWithIdentifier:@"basicCell" forIndexPath:indexPath];
            basicCell.selectionStyle = UITableViewCellSelectionStyleNone;
            basicCell.canEdit = self.canEditBasic;
            basicCell.dataDic = self.resultDic;
            [basicCell.indexTF addTarget:self action:@selector(indexNumberEditingChanged:) forControlEvents:UIControlEventEditingChanged];
            [basicCell.doctorBtn addTarget:self action:@selector(selectDoctorAction) forControlEvents:UIControlEventTouchUpInside];
            return basicCell;
            
        }else if (indexPath.row == 1 || indexPath.row == 2){
            //类型、问诊需求
            LGConsultRecordItemCell *itemCell = [tableView dequeueReusableCellWithIdentifier:@"itemCell" forIndexPath:indexPath];
            itemCell.selectionStyle = UITableViewCellSelectionStyleNone;
            itemCell.title = (indexPath.row == 1)?@"类型":@"问诊需求(可多选)";
            itemCell.type = (indexPath.row == 1)?@"radio":@"multiple";
            NSString *result = (indexPath.row == 1)?LGNSString(self.resultDic[@"followup_type"]):LGNSString(self.resultDic[@"follow_needs"]);
            itemCell.resultArray = [result componentsSeparatedByString:@","];
            itemCell.itemArray = (indexPath.row == 1)?self.typeArray:self.needArray;
            itemCell.delegate = self;
            return itemCell;
            
        }else if (indexPath.row == 3){
            //共病类型
            LGConsultRecordDiseaseCell *diseaseCell = [tableView dequeueReusableCellWithIdentifier:@"diseaseCell" forIndexPath:indexPath];
            diseaseCell.selectionStyle = UITableViewCellSelectionStyleNone;
            diseaseCell.resultArray = self.diseaseArray;
            diseaseCell.delegate = self;
            return diseaseCell;
            
        }else if (indexPath.row == 4 || indexPath.row == 5){
            //吸烟、饮酒史
            LGConsultRecordHistoryCell *historyCell = [tableView dequeueReusableCellWithIdentifier:@"historyCell" forIndexPath:indexPath];
            historyCell.selectionStyle = UITableViewCellSelectionStyleNone;
            historyCell.type = (indexPath.row == 4)?@"smoke":@"drink";
            historyCell.delegate = self;
            historyCell.dataDic = (indexPath.row == 4)?self.smokeDic:self.drinkDic;
            return historyCell;
        }
    }else if (indexPath.section == 1){
        //手术信息
        LGConsultRecordSurgeryCell *surgeryCell = [tableView dequeueReusableCellWithIdentifier:@"surgeryCell" forIndexPath:indexPath];
        surgeryCell.selectionStyle = UITableViewCellSelectionStyleNone;
        surgeryCell.content = LGNSString(self.surgeryArray[indexPath.row]);
        return surgeryCell;
        
    }else if (indexPath.section == 2){
        //病情描述
        LGConsultRecordDescCell *descCell = [tableView dequeueReusableCellWithIdentifier:@"descCell" forIndexPath:indexPath];
        descCell.selectionStyle = UITableViewCellSelectionStyleNone;
        descCell.content = LGNSString(self.resultDic[@"followup_content"]);
        descCell.tableView = self.tableView;
        descCell.delegate = self;
        return descCell;
        
    }else if (indexPath.section == 3){
        //体征监测
        LGConsultRecordMonitorCell *monitorCell = [tableView dequeueReusableCellWithIdentifier:@"monitorCell" forIndexPath:indexPath];
        monitorCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [monitorCell.highPressureTF addTarget:self action:@selector(monitorTextFiledEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        [monitorCell.lowPressureTF addTarget:self action:@selector(monitorTextFiledEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        [monitorCell.heartRateTF addTarget:self action:@selector(monitorTextFiledEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        [monitorCell.heightTF addTarget:self action:@selector(monitorTextFiledEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        [monitorCell.weightTF addTarget:self action:@selector(monitorTextFiledEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        [monitorCell.abdominalTF addTarget:self action:@selector(monitorTextFiledEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        [monitorCell.heartGradeBtn addTarget:self action:@selector(selectHeartGradeAction) forControlEvents:UIControlEventTouchUpInside];
        monitorCell.highPressureTF.text = LGNSString(self.resultDic[@"sbp"]);
        monitorCell.lowPressureTF.text = LGNSString(self.resultDic[@"dbp"]);
        monitorCell.heartRateTF.text = LGNSString(self.resultDic[@"pulse"]);
        monitorCell.heightTF.text = LGNSString(self.resultDic[@"height"]);
        monitorCell.weightTF.text = LGNSString(self.resultDic[@"weight"]);
        monitorCell.abdominalTF.text = LGNSString(self.resultDic[@"acvalue"]);
        monitorCell.heartGradeTF.text = LGNSString(self.resultDic[@"nyha"]);
        
        return monitorCell;
        
    }else if (indexPath.section == 4){
        //检验检查
        LGConsultRecordInpectCell *inspectCell = [tableView dequeueReusableCellWithIdentifier:@"inspectCell"];
        inspectCell.selectionStyle = UITableViewCellSelectionStyleNone;
        inspectCell.photoArray = self.inspectArray;
        [inspectCell.uploadBtn addTarget:self action:@selector(uploadInspectReport) forControlEvents:UIControlEventTouchUpInside];
        [inspectCell.addButton addTarget:self action:@selector(addCoreIndicators) forControlEvents:UIControlEventTouchUpInside];
        __weak typeof(self) weakSelf = self;
        inspectCell.checkMorePhotoAction = ^{
            [weakSelf uploadInspectReport];
        };
        return inspectCell;
        
    }else if (indexPath.section == 5){
        //用药记录
        if(indexPath.row == 0){
            LGConsultRecordDateCell *dateCell = [tableView dequeueReusableCellWithIdentifier:@"dateCell" forIndexPath:indexPath];
            dateCell.selectionStyle = UITableViewCellSelectionStyleNone;
            dateCell.content = LGNSString(self.resultDic[@"followup_date"]);
            return dateCell;
            
        }else{
            LGConsultRecordMedicineCell *medicineCell = [tableView dequeueReusableCellWithIdentifier:@"medicineCell" forIndexPath:indexPath];
            medicineCell.selectionStyle = UITableViewCellSelectionStyleNone;
            medicineCell.canEdit = YES;
            medicineCell.dataDic = self.medicineArray[indexPath.row-1];
            return medicineCell;
        }
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        //编辑手术信息
        NSDictionary *tempDic = self.surgeryArray[indexPath.row];
        NSString *ispatient = LGNSString(tempDic[@"is_patient"]);
        if(![ispatient isEqualToString:@"Y"]){
            //患者自填的不可跳转
            LGFollowOperationController *controller = [[LGFollowOperationController alloc]init];
            controller.patientid = self.patientid;
            controller.dataDic = tempDic;
            [self.navigationController pushViewController:controller animated:YES];
        }
        
    }else if (indexPath.section == 5){
        //编辑用药记录
        __block NSInteger index = indexPath.row-1;
        NSDictionary *tempDic = self.medicineArray[indexPath.row-1];
        if([tempDic[@"advice_type"] isEqualToString:@"in"]){
            //设置实际用药
            LGMedicineStatisticAlertView *alertView = [[LGMedicineStatisticAlertView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
            [[UIApplication sharedApplication].keyWindow addSubview:alertView];
            __weak typeof(self) weakSelf = self;
            alertView.selectCondition = ^(NSString * _Nonnull type) {
                __block NSMutableDictionary *muteDic = [NSMutableDictionary dictionaryWithDictionary:weakSelf.medicineArray[index]];
                if([type isEqualToString:@"other"]){
                    //其他
                    LGPickerViewMax *pickerView = [[LGPickerViewMax alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
                    pickerView.unitOffset = viewPix(40);
                    pickerView.pickArry = @[self.doseArray,self.rateArray];
                    pickerView.units = @[LGNSString(muteDic[@"dose_unit"]),@""];
                    pickerView.selectStr = @"1|每日一次";
                    pickerView.titleLabel.text = @"其他用药情况";
                    [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
                    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
                        [muteDic setValue:LGNSString(resultArray[0]) forKey:@"reality_dose"];
                        [muteDic setValue:LGNSString(resultArray[1]) forKey:@"reality_take_frequency"];
                        [weakSelf.medicineArray replaceObjectAtIndex:index withObject:muteDic];
                        [weakSelf.tableView reloadData];
                    };
                    
                    
                }else if([type isEqualToString:@"-2"]){
//                    [muteDic setValue:type forKey:@"reality_dose"];
//                    [weakSelf.statisticArray replaceObjectAtIndex:index withObject:muteDic];
//                    [weakSelf.tableView reloadData];
                    //填写停药原因
                    LGFollowStopMedicineController *controller = [[LGFollowStopMedicineController alloc]init];
                    controller.index = index;
                    controller.content = LGNSString(muteDic[@"stop_desc"]);
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                    controller.stopDescFillComplete = ^(NSString * _Nonnull content, NSInteger index) {
                        NSMutableDictionary *stopDic = weakSelf.medicineArray[index];
                        [stopDic setValue:@"-2" forKey:@"reality_dose"];
                        [stopDic setValue:content forKey:@"stop_desc"];
                        [weakSelf.medicineArray replaceObjectAtIndex:index withObject:stopDic];
                        [weakSelf.tableView reloadData];
                    };
                    
                }else{
                    [muteDic setValue:type forKey:@"reality_dose"];
                    [weakSelf.medicineArray replaceObjectAtIndex:index withObject:muteDic];
                    [weakSelf.tableView reloadData];
                }
            };
        }else{
            //修改医嘱外用药
            LGFollowAddMedicineController *controller = [[LGFollowAddMedicineController alloc]init];
            controller.dataDic = self.medicineArray[indexPath.row-1];
            controller.index = indexPath.row-1;
            [self.navigationController pushViewController:controller animated:YES];
            __weak typeof(self) weakSelf = self;
            controller.deleteMedicineRecord = ^(NSInteger index) {
                [weakSelf.medicineArray removeObjectAtIndex:index];
                [weakSelf.tableView reloadData];
//                weakSelf.popBack = NO;
//                [weakSelf saveFollowData:@"N" withCheck:NO];
            };
            controller.editMedicineRecord = ^(NSDictionary * _Nonnull tempDic, NSInteger index) {
                [weakSelf.medicineArray replaceObjectAtIndex:index withObject:tempDic];
                [weakSelf.tableView reloadData];
//                weakSelf.popBack = NO;
//                [weakSelf saveFollowData:@"N" withCheck:NO];
            };
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 1){
        return viewPix(30);
        
    }else if (section == 2){
        return 0.01;
    }else{
        return viewPix(56);
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 1){
        LGCornerHeaderView *headerView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(30))];
        headerView.topMargin = -viewPix(16);
        UILabel *titleLabel = [UILabel lableWithText:@"手术信息" colorString:@"#333333" textFont:LGFontWeight(15, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        titleLabel.frame = CGRectMake(viewPix(28), 0, viewPix(150), viewPix(30));
        [headerView addSubview:titleLabel];
        return headerView;
        
    }else if(section == 2){
        return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
        
    }else{
        LGDiseaseOverviewHeaderView *headerView = [[LGDiseaseOverviewHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(56))];
        headerView.showTip = (section == 4)?YES:NO;
        headerView.title = self.sectionArray[section];
        headerView.subTitle = (section == 4)?@"查看全部":@"";
        if(section == 4){
            [headerView.actionBtn addTarget:self action:@selector(checkMoreInspectAction) forControlEvents:UIControlEventTouchUpInside];
        }
        return headerView;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 0){
        return 0.01;
    }else if (section == 1){
        return viewPix(40);
    }else if (section == 5){
        return viewPix(45);
    }else{
        return viewPix(15);
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NSArray *heightArray = @[@(0.01),@(viewPix(40)),@(viewPix(15)),@(viewPix(15)),@(viewPix(15)),@(viewPix(45))];
    LGCornerFooterView *footerView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, [heightArray[section] floatValue])];
    footerView.backgroundColor = [UIColor clearColor];
    if (section == 1 || section == 5){
        footerView.bottomMargin = (section == 1)?-viewPix(16):viewPix(5);
        NSString *title = (section == 1)?@"添加手术":@"添加药物";
        UIButton *addBtn = [UIButton buttonWithTitle:title titleFont:LGFontWeight(15, UIFontWeightMedium) textColor:@"#3291FF" imageName:@""];
        addBtn.frame = CGRectMake(viewPix(28), viewPix(2), Screen_W-viewPix(56), viewPix(32));
        addBtn.layer.borderColor = [UIColor colorWithString:@"#3291FF"].CGColor;
        addBtn.layer.borderWidth = 1;
        addBtn.layer.cornerRadius = viewPix(16);
        addBtn.tag = 1000+section;
        [addBtn addTarget:self action:@selector(addButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:addBtn];
    }else{
        footerView.bottomMargin = (section == 0)?0:viewPix(8);
    }
    return footerView;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight-viewPix(72)-bottomSafeBarHeight/3.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGConsultRecordBasicCell class] forCellReuseIdentifier:@"basicCell"];
        [_tableView registerClass:[LGConsultRecordItemCell class] forCellReuseIdentifier:@"itemCell"];
        [_tableView registerClass:[LGConsultRecordDiseaseCell class] forCellReuseIdentifier:@"diseaseCell"];
        [_tableView registerClass:[LGConsultRecordHistoryCell class] forCellReuseIdentifier:@"historyCell"];
        [_tableView registerClass:[LGConsultRecordSurgeryCell class] forCellReuseIdentifier:@"surgeryCell"];
        [_tableView registerClass:[LGConsultRecordDescCell class] forCellReuseIdentifier:@"descCell"];
        [_tableView registerClass:[LGConsultRecordMonitorCell class] forCellReuseIdentifier:@"monitorCell"];
        [_tableView registerClass:[LGConsultRecordInpectCell class] forCellReuseIdentifier:@"inspectCell"];
        [_tableView registerClass:[LGConsultRecordMedicineCell class] forCellReuseIdentifier:@"medicineCell"];
        [_tableView registerClass:[LGConsultRecordDateCell class] forCellReuseIdentifier:@"dateCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedRowHeight = UITableViewAutomaticDimension;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(void)createBottomView{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(72)+bottomSafeBarHeight/3.0)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    UIButton *saveBtn = [UIButton buttonWithTitle:@"保存" topMargin:viewPix(8)];
    [saveBtn addTarget:self action:@selector(saveDataAction) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:saveBtn];
    self.bottomeView = bottomView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
